package com.northpool.operator.common.xml;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import com.alibaba.fastjson.JSONObject;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.exception.ParamException;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.type.TypeEnum;
import com.northpool.operator.utils.StpOperatorHelper;

@OperatorInfo(
        ref = "Json2XmlOperator",
        name = "JSON转XML",
        description = "JSON字符串转XML字符串",
        version = "1.0.0"
)
@OutputParams({
        @OutputParam(ref = "result", name = "XML", desc = "XML字符串")
})
public class Json2XmlOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "json", name = "JSON", desc = "JSON字符串", type = TypeEnum.STRING, required = true),
            @InputParam(ref = "rootName", name = "根节点名称", desc = "根节点名称", type = TypeEnum.STRING, required = false, value = "xml"),
            @InputParam(ref = "pretty", name = "美化", desc = "是否美化", type = TypeEnum.BOOL, required = false, value = "false"),
            @InputParam(ref = "omitXmlDeclaration", name = "忽略声明", desc = "是否忽略声明头", type = TypeEnum.BOOL, required = false, value = "false")
    })
    public Json2XmlOperator() {
    }

    public static void main(String[] args) {
        OperatorTestBuild.execute(Json2XmlOperator.class, TestParamBuilder.aBuilder()
                .param("json", "{\"name\":\"张三\",\"age\":18}")
                .param("rootName", "person")
                .param("pretty", "true")
                .param("omitXmlDeclaration", "true")
                .build());
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String jsonStr = paramTool.getStr("json");
        String rootName = paramTool.getStr("rootName");
        Boolean pretty = paramTool.getBool("pretty");
        Boolean omitXmlDeclaration = paramTool.getBool("omitXmlDeclaration");
        if (StrUtil.isBlank(jsonStr)) {
            throw new ParamException("json", "json字符串不能为空");
        }

        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String xml = XmlUtil.mapToXmlStr(jsonObject, rootName, "", "utf-8",  pretty,  omitXmlDeclaration);
        this.result("result", xml);
    }
}
